package com.example.server.service.implement;

import com.example.server.service.CaptchaService;
import com.example.server.utils.EmailUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class CaptchaServiceImpl implements CaptchaService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    EmailUtil emailUtil;
    @Override
    public boolean sendCaptcha(String email) {
        return sendMailCaptcha("login:email:captcha:"+email);
    }

    @Override
    public boolean verifyCaptcha(String email, String captcha) {
        String key = "login:email:captcha:" + email;
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(key);
        // 从 Redis 中获取存储的验证码
        String storedCaptcha = hashOps.get("captcha");
        if (StringUtils.isBlank(storedCaptcha)) {
            throw new RuntimeException("验证码已失效");
        }
        if (!storedCaptcha.equals(captcha)) {
            throw new RuntimeException("验证码不正确");
        }
        // 验证通过后删除验证码以防复用
        stringRedisTemplate.delete(key);
        return true;
    }

    private boolean  sendMailCaptcha(String key) {
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(key);
        // 初始检查
        String lastSendTimestamp = hashOps.get("lastSendTimestamp");
        String sendCount = hashOps.get("sendCount");

        if(StringUtils.isNotBlank(sendCount)&&Integer.parseInt(sendCount)>=5){
            hashOps.expire(24, TimeUnit.HOURS);
            throw new  RuntimeException("验证码发送过于频繁");
        }
        if(StringUtils.isNotBlank(lastSendTimestamp)){
            long lastSendTime = Long.parseLong(lastSendTimestamp);
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - lastSendTime;
            if(elapsedTime < 60 * 1000){
                throw new  RuntimeException("验证码发送过于频繁");
            }
        }
        int newSendCount = StringUtils.isNotBlank(sendCount) ? Integer.parseInt(sendCount) + 1 : 1;
        String captcha = RandomStringUtils.randomNumeric(6);

        try {
            sendCaptcha(key,captcha);
        } catch (Exception e) {
            return false;
        }
        hashOps.put("captcha", captcha);
        hashOps.put("lastSendTimestamp", String.valueOf(System.currentTimeMillis()));
        hashOps.put("sendCount", String.valueOf(newSendCount));
        hashOps.expire(5, TimeUnit.MINUTES); // 设置过期时间为5分钟

        return true;

    }

    private void sendCaptcha(String hashKey, String captcha) throws Exception{
        if("email".equals(hashKey.split(":")[1])){
            String subject = "登录验证"; // 邮件主题
            String template = "<html><body>用户您好，您的验证码是:<h1>%s</h1>请在五分钟内完成注册</body></html>"; // 邮件模板
            String content = String.format(template, captcha); // 格式化邮件内容

            if (!emailUtil.sendHtmlEmail(subject, content, hashKey.split(":")[3])) {
                throw new RuntimeException("发送邮件失败");
            }
        }
    }
}
